package com.dkd.common;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import java.io.File;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";

        // 方法1：从环境变量读取 AccessKey（推荐）
        // 运行前需设置环境变量 OSS_ACCESS_KEY_ID 和 OSS_ACCESS_KEY_SECRET
        CredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        // 方法2：硬编码 AccessKey（仅测试用，生产环境不安全）
        // String accessKeyId = "LTAI5tKMqin1KgeZaEgymARs";
        // String accessKeySecret = "uKW20m8AJXUKz92w0nXSDo6zy3qb9n";
        // CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);

        // 填写Bucket名称
        String bucketName = "lbwnb123";
        // 填写Object完整路径
        String objectName = "Screenshot 2024-10-23 221630.jpg";
        // 填写本地文件的完整路径
        String filePath = "C:\\Users\\Asus\\OneDrive\\Pictures\\Screenshot 2024-10-23 221630.jpg";
        // Bucket所在地域
        String region = "cn-beijing";

        // 配置客户端（使用 V4 签名）
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);

        // 创建OSSClient实例（仅初始化一次）
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath));

            // 上传文件
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            System.out.println("上传成功！ETag: " + result.getETag());

        } catch (OSSException oe) {
            System.out.println("OSS异常:");
            System.out.println("错误信息: " + oe.getErrorMessage());
            System.out.println("错误码: " + oe.getErrorCode());
            System.out.println("请求ID: " + oe.getRequestId());
        } catch (ClientException ce) {
            System.out.println("客户端异常:");
            System.out.println("错误信息: " + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}